@echo off
set FMU_MODEL_PATH=%1
set EXTRACTED_FMU_PATH=%2
set MSBUILD_PATH=%3
set PROJECT_PATH=%4
set BUILD_EXE_PATH=%5
set UPPER_PROJECT_PATH=%6
set OUTPUT_LOG_PATH=%7

echo Checking if the FMU file exists...
if not exist "%FMU_MODEL_PATH%" (
    echo ERROR: FMU file not found at "%FMU_MODEL_PATH%"
    exit /b 1
)

echo Killing any running instances of the application...
taskkill /F /IM testno.exe /T

echo Deleting old extracted model directory...
if exist "%EXTRACTED_FMU_PATH%\*" rmdir /S /Q "%EXTRACTED_FMU_PATH%"
if not exist "%EXTRACTED_FMU_PATH%" mkdir "%EXTRACTED_FMU_PATH%"

echo Deleting old executable files...
if exist "%BUILD_EXE_PATH%" del /F "%BUILD_EXE_PATH%"

echo Extracting FMU file...
tar -xf "%FMU_MODEL_PATH%" -C "%EXTRACTED_FMU_PATH%"

echo Updating Visual Studio project files...
powershell -File "update_vcxproj.ps1" -vcxprojPath "%PROJECT_PATH%" -sourceDirectory "%EXTRACTED_FMU_PATH%\Sources"

echo Cleaning the Visual Studio project...
"%MSBUILD_PATH%" "%UPPER_PROJECT_PATH%" -t:Clean

echo Building the project...
"%MSBUILD_PATH%" "%UPPER_PROJECT_PATH%" -t:Build -p:Configuration=Release -p:Platform="x64" -m

echo Checking if the executable exists...
if exist "%BUILD_EXE_PATH%" (
    echo Running the executable...
    "%BUILD_EXE_PATH%" > "%OUTPUT_LOG_PATH%" 2>&1
) else (
    echo WARNING: The executable does not exist. Check build process or path.
)

echo Process completed.
